package com.symbol.Tools;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.swing.JFrame;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.google.zxing.qrcode.encoder.ByteMatrix;
import com.google.zxing.qrcode.encoder.Encoder;
import com.google.zxing.qrcode.encoder.QRCode;

/**
 * 整个二维码转换为图片
 * 
 * @author symbol
 *
 */
public class ImageLogoQRCode {
	
	/**
     * For more information about QR code, refer to: https://en.wikipedia.org/wiki/QR_code
     * BYTE_EPT: Empty block
     * BYTE_DTA: Data block
     * BYTE_POS: Position block
     * BYTE_AGN: Align block
     * BYTE_TMG: Timing block
     * BYTE_PTC: Protector block, translucent layer (custom block, this is not included in QR code's standards)
     */
    private static final int BYTE_EPT = 0x0;
    private static final int BYTE_DTA = 0x1;
    private static final int BYTE_POS = 0x2;
    private static final int BYTE_AGN = 0x3;
    private static final int BYTE_TMG = 0x4;
    private static final int BYTE_PTC = 0x5;

    private static float DEFAULT_DTA_DOT_SCALE = 0.3f;
    private static float DEFAULT_LOGO_SCALE = 0.2f;
    private static int DEFAULT_SIZE = 800;
    private static int DEFAULT_MARGIN = 20;
    private static int DEFAULT_LOGO_MARGIN = 10;
    private static int DEFAULT_LOGO_RADIUS = 8;
    private static int DEFAULT_BINARIZING_THRESHOLD = 128;

	private static MultiFormatWriter mutiWriter = new MultiFormatWriter();

	/**
	 * 制作一个艺术图片二维码
	 * 
	 * @param content
	 *            内容
	 * @param width
	 *            二维码宽度
	 * @param height
	 *            二维码高度
	 * @param srcImagePath
	 *            图片路径
	 * @param stream
	 *            输出路径
	 * @throws WriterException
	 * @throws IOException
	 * 
	 */
	public void getPhotoQrCode(String content, int width, int height, String srcImagePath, OutputStream stream)
			throws WriterException, IOException {
		int FRAME_WIDTH = 2;
		int IMAGE_HALF_WIDTH = width / 2;
		// 读取logo源图像
		BufferedImage scaleImage = scale(srcImagePath, width, height, false);
		int[][] srcPixels = new int[width][height];
		for (int i = 0; i < scaleImage.getWidth(); i++) {
			for (int j = 0; j < scaleImage.getHeight(); j++) {
				srcPixels[i][j] = scaleImage.getRGB(i, j);
			}
		}
		
		// 生成二维码
//		BitMatrix matrix = mutiWriter.encode(content, BarcodeFormat.QR_CODE, width, height, hint);
		ByteMatrix byteMatrix = getBitMatrix(content);//获取一个二维码
		
		// 二维矩阵转为一维像素数组
//		int halfW = matrix.getWidth() / 2;
//		int halfH = matrix.getHeight() / 2;
//		int[] pixels = new int[width * height];

		for (int y = 0; y < byteMatrix.getHeight(); y++) {
			for (int x = 0; x < byteMatrix.getWidth(); x++) {
				
				switch (byteMatrix.get(x, y)) {
                case BYTE_AGN:
                case BYTE_POS:
                case BYTE_TMG:
                    canvas.drawRect(
                            margin + col * nWidth,
                            margin + row * nHeight,
                            margin + (col + 1.0f) * nWidth,
                            margin + (row + 1.0f) * nHeight,
                            paintDark
                    );
                    break;
                case BYTE_DTA:
                    if (roundedDataDots) {
                        canvas.drawCircle(
                                margin + (col + 0.5f) * nWidth,
                                margin + (row + 0.5f) * nHeight,
                                dataDotScale * nHeight * 0.5f,
                                paintDark
                        );
                    } else {
                        canvas.drawRect(
                                margin + (col + 0.5f * (1 - dataDotScale)) * nWidth,
                                margin + (row + 0.5f * (1 - dataDotScale)) * nHeight,
                                margin + (col + 0.5f * (1 + dataDotScale)) * nWidth,
                                margin + (row + 0.5f * (1 + dataDotScale)) * nHeight,
                                paintDark
                        );
                    }
                    break;
                case BYTE_PTC:
                    canvas.drawRect(
                            margin + col * nWidth,
                            margin + row * nHeight,
                            margin + (col + 1.0f) * nWidth,
                            margin + (row + 1.0f) * nHeight,
                            paintProtector
                    );
                    break;
                case BYTE_EPT:
                    if (roundedDataDots) {
                        canvas.drawCircle(
                                margin + (col + 0.5f) * nWidth,
                                margin + (row + 0.5f) * nHeight,
                                dataDotScale * nHeight * 0.5f,
                                paintLight
                        );
                    } else {
                        canvas.drawRect(
                                margin + (col + 0.5f * (1 - dataDotScale)) * nWidth,
                                margin + (row + 0.5f * (1 - dataDotScale)) * nHeight,
                                margin + (col + 0.5f * (1 + dataDotScale)) * nWidth,
                                margin + (row + 0.5f * (1 + dataDotScale)) * nHeight,
                                paintLight
                        );
                    }
                    break;
            }
				
				// 读取图片
//				if (x > halfW - IMAGE_HALF_WIDTH && x < halfW + IMAGE_HALF_WIDTH && y > halfH - IMAGE_HALF_WIDTH
//						&& y < halfH + IMAGE_HALF_WIDTH) {
//					pixels[y * width + x] = srcPixels[x - halfW + IMAGE_HALF_WIDTH][y - halfH + IMAGE_HALF_WIDTH];
//				}
				// 在图片四周形成边框
//				else if ((x > halfW - IMAGE_HALF_WIDTH - FRAME_WIDTH && x < halfW - IMAGE_HALF_WIDTH + FRAME_WIDTH
//						&& y > halfH - IMAGE_HALF_WIDTH - FRAME_WIDTH && y < halfH + IMAGE_HALF_WIDTH + FRAME_WIDTH)
//						|| (x > halfW + IMAGE_HALF_WIDTH - FRAME_WIDTH && x < halfW + IMAGE_HALF_WIDTH + FRAME_WIDTH
//								&& y > halfH - IMAGE_HALF_WIDTH - FRAME_WIDTH
//								&& y < halfH + IMAGE_HALF_WIDTH + FRAME_WIDTH)
//						|| (x > halfW - IMAGE_HALF_WIDTH - FRAME_WIDTH && x < halfW + IMAGE_HALF_WIDTH + FRAME_WIDTH
//								&& y > halfH - IMAGE_HALF_WIDTH - FRAME_WIDTH
//								&& y < halfH - IMAGE_HALF_WIDTH + FRAME_WIDTH)
//						|| (x > halfW - IMAGE_HALF_WIDTH - FRAME_WIDTH && x < halfW + IMAGE_HALF_WIDTH + FRAME_WIDTH
//								&& y > halfH + IMAGE_HALF_WIDTH - FRAME_WIDTH
//								&& y < halfH + IMAGE_HALF_WIDTH + FRAME_WIDTH)) {
//					pixels[y * width + x] = 0xfffffff;
//				} 
//				else {
//					// 此处可以修改二维码的颜色，可以分别制定二维码和背景的颜色；
//					pixels[y * width + x] = matrix.get(x, y) ? 0xff000000 : 0xfffffff;
//				}
			}
		}

		BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		image.getRaster().setDataElements(0, 0, width, height, pixels);

		ImageIO.write(image, "png", stream);
	}
	
	private static ByteMatrix getBitMatrix(String contents) {
        try {
        	Map<EncodeHintType, Object> hint = new HashMap<EncodeHintType, Object>();
    		hint.put(EncodeHintType.CHARACTER_SET, "utf-8");
    		hint.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
            QRCode qrCode = Encoder.encode(contents, ErrorCorrectionLevel.H, hint);
            int agnCenter[] = qrCode.getVersion().getAlignmentPatternCenters();
            ByteMatrix byteMatrix = qrCode.getMatrix();
            int matSize = byteMatrix.getWidth();
            for (int row = 0; row < matSize; row++) {
                for (int col = 0; col < matSize; col++) {
                    if (isTypeAGN(col, row, agnCenter, true)) {
                        if (byteMatrix.get(col, row) != BYTE_EPT) {
                            byteMatrix.set(col, row, BYTE_AGN);
                        } else {
                            byteMatrix.set(col, row, BYTE_PTC);
                        }
                    } else if (isTypePOS(col, row, matSize, true)) {
                        if (byteMatrix.get(col, row) != BYTE_EPT) {
                            byteMatrix.set(col, row, BYTE_POS);
                        } else {
                            byteMatrix.set(col, row, BYTE_PTC);
                        }
                    } else if (isTypeTMG(col, row, matSize)) {
                        if (byteMatrix.get(col, row) != BYTE_EPT) {
                            byteMatrix.set(col, row, BYTE_TMG);
                        } else {
                            byteMatrix.set(col, row, BYTE_PTC);
                        }
                    }

                    if (isTypePOS(col, row, matSize, false)) {
                        if (byteMatrix.get(col, row) == BYTE_EPT) {
                            byteMatrix.set(col, row, BYTE_PTC);
                        }
                    }
                }
            }
            return byteMatrix;
        } catch (WriterException e) {
            e.printStackTrace();
        }
        return null;
    }
	
    private static boolean isTypeTMG(int x, int y, int size) {
        return ((y == 6 && (x >= 8 && x < size - 8)) || (x == 6 && (y >= 8 && y < size - 8)));
    }
	
    private static boolean isTypePOS(int x, int y, int size, boolean inner) {
        if (inner) {
            return ((x < 7 && (y < 7 || y >= size - 7)) || (x >= size - 7 && y < 7));
        } else {
            return ((x <= 7 && (y <= 7 || y >= size - 8)) || (x >= size - 8 && y <= 7));
        }
    }
	
    private static boolean isTypeAGN(int x, int y, int[] agnCenter, boolean edgeOnly) {
        if (agnCenter.length == 0) return false;
        int edgeCenter = agnCenter[agnCenter.length - 1];
        for (int agnY : agnCenter) {
            for (int agnX : agnCenter) {
                if (edgeOnly && agnX != 6 && agnY != 6 && agnX != edgeCenter && agnY != edgeCenter)
                    continue;
                if ((agnX == 6 && agnY == 6) || (agnX == 6 && agnY == edgeCenter) || (agnY == 6 && agnX == edgeCenter))
                    continue;
                if (x >= agnX - 2 && x <= agnX + 2 && y >= agnY - 2 && y <= agnY + 2)
                    return true;
            }
        }
        return false;
    }

	/**
	 * 把传入的原始图像按高度和宽度进行缩放，生成符合要求的图标
	 * 
	 * @param srcImageFile
	 *            源文件地址
	 * @param height
	 *            目标高度
	 * @param width
	 *            目标宽度
	 * @param hasFiller
	 *            比例不对时是否需要补白：true为补白; false为不补白;
	 * @throws IOException
	 */
	private static BufferedImage scale(String srcImageFile, int height, int width, boolean hasFiller)
			throws IOException {
		double ratio = 0.0; // 缩放比例
		File file = new File(srcImageFile);
		BufferedImage srcImage = ImageIO.read(file);
		Image destImage = srcImage.getScaledInstance(width, height, BufferedImage.SCALE_SMOOTH);
		// 计算比例
		if ((srcImage.getHeight() > height) || (srcImage.getWidth() > width)) {
			if (srcImage.getHeight() > srcImage.getWidth()) {
				ratio = (new Integer(height)).doubleValue() / srcImage.getHeight();
			} else {
				ratio = (new Integer(width)).doubleValue() / srcImage.getWidth();
			}
			AffineTransformOp op = new AffineTransformOp(AffineTransform.getScaleInstance(ratio, ratio), null);
			destImage = op.filter(srcImage, null);
		}
		if (hasFiller) {// 补白
			BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
			Graphics2D graphic = image.createGraphics();
			graphic.setColor(Color.white);
			graphic.fillRect(0, 0, width, height);
			if (width == destImage.getWidth(null))
				graphic.drawImage(destImage, 0, (height - destImage.getHeight(null)) / 2, destImage.getWidth(null),
						destImage.getHeight(null), Color.white, null);
			else
				graphic.drawImage(destImage, (width - destImage.getWidth(null)) / 2, 0, destImage.getWidth(null),
						destImage.getHeight(null), Color.white, null);
			graphic.dispose();
			destImage = image;
		}
		return (BufferedImage) destImage;
	}

}
